import { createSlice } from "@reduxjs/toolkit"

const tagsView = createSlice({
	name: 'tagsView',
	initialState: {
		activeTagId: '/',
		openKey: [],
		defaultSelectedKey: [],
		tags: [],
	},
	reducers: {
		setopenKey(state, { payload }) {
			console.log("======setopenKey====",payload)
			state.openKey = payload;
		},
		setselectedKey(state, { payload }) {
			console.log("======setselectedKey====",payload)
			state.defaultSelectedKey = payload;
		},
		setActiveTag(state, { payload }) {
			//console.log("======setActiveTag====",payload)
			state.activeTagId = payload;
		},
		addTag(state, { payload }) {
			if (!state.tags.find(tag => tag.path === payload.path)) {
				state.tags.push(payload);
			}

			state.activeTagId = payload.path;
		},
		removeTag(state, { payload }) {
			console.log("======removeTagremoveTag====",payload)
			const targetKey = payload;
			// dashboard cloud't be closed

			if (targetKey === state.tags[0].path) {
				return;
			}

			const activeTagId = state.activeTagId;
			let lastIndex = 0;

			state.tags.forEach((tag, i) => {
				if (tag.path === targetKey) {
					state.tags.splice(i, 1);
					lastIndex = i - 1;
				}
			});
			const tagList = state.tags.filter(tag => tag.path !== targetKey);

			if (tagList.length && activeTagId === targetKey) {
				if (lastIndex >= 0) {
					state.activeTagId = tagList[lastIndex].path;
				} else {
					state.activeTagId = tagList[0].path;
				}
			}
		},
		removeAllTag(state) {
			state.activeTagId = state.tags[0].path;
			state.tags = [state.tags[0]];
		},
		removeOtherTag(state) {
			const activeTag = state.tags.find(tag => tag.path === state.activeTagId);
			//const activeIsDashboard = activeTag.path === state.tags[0].path;
			const activeIsDashboard = activeTag.path;

			state.tags = activeIsDashboard ? [state.tags[0]] : [state.tags[0], activeTag];
		},
	},
});

export const { setopenKey, setselectedKey, setActiveTag, addTag, removeTag, removeAllTag, removeOtherTag } = tagsView.actions;

export default tagsView.reducer;
